/*
 * Copyright 2020 www.mytijian.com All right reserved. This software is the
 * confidential and proprietary information of www.mytijian.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with www.mytijian.com.
 */
package com.mytijian.task.controller;

import com.google.common.collect.Lists;
import com.mytijian.account.dto.BatchImportCustomerDTO;
import com.mytijian.base.exception.BizException;
import com.mytijian.task.enums.TaskStatusEnum;
import com.mytijian.task.model.SubmitTask;
import com.mytijian.task.zookeeper.path.NodePath;
import com.mytijian.task.enums.SubTaskStatusEnum;
import com.mytijian.task.httprequest.HttpRequest;
import com.mytijian.task.httprequest.RestTemplateBuilder;
import com.mytijian.task.model.SubTask;
import com.mytijian.task.model.Task;
import com.mytijian.task.repository.TaskRepository;
import com.mytijian.task.repository.model.GroupExecutorDTO;
import com.mytijian.task.task.TaskOperateService;
import com.mytijian.task.zookeeper.ZookeeperRegistryCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/controller")
public class TaskController {
    private Logger logger = LoggerFactory.getLogger(TaskController.class);
    @Autowired
    private TaskRepository taskRepository;
    @Autowired
    private ZookeeperRegistryCenter zookeeperRegistryCenter;
    @Autowired
    private TaskOperateService taskOperateService;
    @Autowired
    private ServerProperties serverProperties;
    @GetMapping(value = "/stop")
    public void stop(Integer taskId) {
        taskOperateService.stop(taskId);
    }
    //todo 不能对停止的任务进行操作，不能对完成的任务进行操作。
    @GetMapping(value = "/suspend")
    public void suspend(Integer taskId) {
        taskOperateService.suspend(taskId);

    }
    @GetMapping(value = "/process")
    public void begin(Integer taskId) {
        taskOperateService.process(taskId);

    }

    @PostMapping(value = "submit")
    public void submit(@RequestBody SubmitTask<BatchImportCustomerDTO> task) {
        taskOperateService.submit(task);
    }
    @GetMapping(value = "/getProcessInfo")
    public Map<String, Object> getTask(Integer taskId) {
        Task task = taskRepository.getTasksByIds(Lists.newArrayList(taskId)).get(0);
        List<SubTask> subTasks = taskRepository.getSubTaskByStatus(taskId, Lists.newArrayList(SubTaskStatusEnum.process_fail.getCode()));
        Map<String, Object> map = new HashMap<>();
        map.put("task", task);
        map.put("failTasks", subTasks);
        return map;
    }
    @PostMapping(value = "/addGroupExecutor")
    public void addGroupExecutor(@RequestBody GroupExecutorDTO groupExecutorDTO) {
        Assert.notNull(groupExecutorDTO.getGroupKey(), "groupKey 不能为空");
        Assert.notNull(groupExecutorDTO.getCapacity(), "capacity 不能为空");
        Assert.notNull(groupExecutorDTO.getWorkThreads(),"workThreads不能为空");
        taskRepository.saveGroupExecutors(groupExecutorDTO);
        Map<String, ResponseEntity> responseEntityHashMap = postRequest("addGroupExecutor", groupExecutorDTO);
        validateResponse(responseEntityHashMap);
    }
    private Map<String, ResponseEntity> postRequest(String operate, Object requestBody) {
        List<String> ipAndPorts =zookeeperRegistryCenter.getChildrenKeys(NodePath.node);
        Map<String, ResponseEntity> responseEntityHashMap = new HashMap<>();
        for (String ipAndPort : ipAndPorts) {
            ResponseEntity responseEntity = postRequest(ipAndPort, operate, requestBody);
            responseEntityHashMap.put(ipAndPort, responseEntity);
        }
        return responseEntityHashMap;
    }
    @PostMapping(value = "modifyGroupExecutor")
    public void modifyGroupExecutor(@RequestBody GroupExecutorDTO groupExecutorDTO) {
        Assert.notNull(groupExecutorDTO.getGroupKey(), "groupKey 不能为空");
        Assert.notNull(groupExecutorDTO.getCapacity(), "capacity 不能为空");
        Assert.notNull(groupExecutorDTO.getWorkThreads(),"workThreads不能为空");
        taskRepository.saveGroupExecutors(groupExecutorDTO);
        Map<String, ResponseEntity> map = postRequest("modifyGroupExecutor", groupExecutorDTO);
        validateResponse(map);
    }
    private void validateResponse(Map<String, ResponseEntity> responseEntityMap) {
        StringBuilder builder = new StringBuilder();
        responseEntityMap.forEach((ipAndPort, jsonObject)->{
            if (responseEntityMap.get(ipAndPort).getStatusCodeValue() != 200) {
                builder.append(ipAndPort).
                        append("节点操作失败:").
                        append(responseEntityMap.get(ipAndPort).getBody()).append('\n');
            }
        });
        if (builder.length() > 0) {
            throw new BizException("12",builder.toString());
        }
    }

    private ResponseEntity postRequest(String ipAndPort, String operate, Object body) {
        return new HttpRequest(serverProperties.getServlet().getContextPath()).postFoRequest(ipAndPort,ControllerConstants.workNode + operate, body);
    }
    private ResponseEntity getRequest(String ipAndPort, String operate, Map<String, Object> param) {
        return new HttpRequest(serverProperties.getServlet().getContextPath()).getForRequest(ipAndPort,ControllerConstants.workNode +operate, param);

    }


    private Map<String, Object> getParams(Integer taskId) {
        Map<String, Object> param = new HashMap<>();
        param.put("taskId", taskId);
        return param;
    }

    public static void main(String[] args) {
        RestTemplate restTemplate = RestTemplateBuilder.buildRestTemplate();
        try {
            ResponseEntity response = restTemplate.getForEntity("http://localhost:8081/isOk", String.class);
            System.out.println(response);
            Object body = response.getBody();
            System.out.println(body);

        }catch (Exception e) {

        }

        //ResponseEntity<Object> response = restTemplate.exchange("http://m-qatest3.mytijian.cn/main/action/validateLogin?_site=mt&_p=&_siteType=mobile&clientVersion=v1.1.6", HttpMethod.GET, request, Object.class);

    }
}
